<?php

namespace backend\models;

use common\helps\tools;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
use yii\db\Query;

/**
 * This is the model class for table "NewProject".
 *
 */
class NewProject extends ActiveRecord
{

    public $type;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%new_project}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return[
            [['title','tags','area','movie_time','release_time','pic','introduction','advertisement','policy','theme','market','case','background_img'], 'trim'],
            [['title','class_id','tags','area','pic','introduction','advertisement','background_img'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','type','class_id','status','is_recommend'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '项目id',
            'title' => '项目名称',
            'class_id'=>'项目分类',
            'tags'=>'类型标签',
            'area'=>'地区',
            'movie_time'=>'片长',
            'release_time'=>'上映时间',
            'pic'=>'封面图',
            'background_img'=>'背景图',
            'status'=>'项目状态',
            'is_recommend'=>'项目是否推荐',
            'introduction'=>'项目简介',
            'advertisement'=>'宣发计划',
            'policy'=>'政策优势',
            'theme'=>'题材优势',
            'market'=>'市场优势',
            'case'=>'相关案例',
            'type'=>'操作类型',
        ];
    }


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'class_id',
                'tags',
                'area',
                'movie_time',
                'release_time',
                'pic',
                'background_img',
                'status',
                'is_recommend',
                'introduction',
                'advertisement',
                'policy',
                'theme',
                'market',
                'case',
                'created_at',
                'updated_at',
                'deleted_at',
                'type',
            ],
            'update_status' => [
                'id',
                'type',
            ],
            'update_project_analyse' => [
                'id',
                'policy',
                'theme',
                'market',
                'case',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'create' => [
                'title',
                'class_id',
                'tags',
                'area',
                'movie_time',
                'release_time',
                'pic',
                'background_img',
                'status',
                'is_recommend',
                'introduction',
                'advertisement',
                'policy',
                'theme',
                'market',
                'case',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update'=>[
                'id',
                'title',
                'class_id',
                'tags',
                'area',
                'movie_time',
                'release_time',
                'pic',
                'background_img',
                'status',
                'is_recommend',
                'introduction',
                'advertisement',
                'policy',
                'theme',
                'market',
                'case',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update_state'=>[
                'id',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
        ];
    }

    /**
     * 获取项目列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectList($params){
        if(!empty($params['title']) && !empty($params['class_id'])){
            $condition = ['and','project_class.id='.trim($params['class_id']),['like','new_project.title',$params['title']],['new_project.deleted_at'=>null]];
        }elseif(!empty($params['title'])){
            $condition = ['and',['like','new_project.title',$params['title']],['new_project.deleted_at'=>null]];
        }elseif(!empty($params['class_id'])){
            $condition =['and','project_class.id='.trim($params['class_id']),['new_project.deleted_at'=>null]];
        }else{
            $condition = ['and','new_project.status=1',['new_project.deleted_at'=>null]];
        }

        $list = (new Query())
            ->select('new_project.id,new_project.pic,new_project.title as name,project_class.title as class,admin.id as user_id,admin.username,new_project.is_recommend,FROM_UNIXTIME(new_project.created_at) as time')
            ->from('new_project')
            ->leftJoin('project_class','project_class.id=new_project.class_id')
            ->leftJoin('admin','admin.id=new_project.uid')
            ->where($condition)
            ->all();
        if(count($list)){
            foreach($list as $key=>$value){
                $list[$key]['user_id'] = $value['username'].'/'.$value['user_id'];
                unset($list[$key]['username']);
            }
        }
        return empty($list)?array():$list;

    }

    /**
     * @inheritdoc
     */
    public static function selectData($field)
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('new_project');
        $query->where(['deleted_at' => null]);
        $command = $query->createCommand();
        $result = $command->queryAll();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($id,$field)
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('new_project');
        $query->where(['deleted_at' => null]);
        $query->andWhere(['id' => $id]);
        $command = $query->createCommand();
        $result = $command->queryOne();
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * 删除与停启用项目
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return boolean
     */
    public  function editProjectState($param){
        $model = static::findOne(['id' =>$param['id']]);
        if(empty($model)) return array('error'=>'未查询到数据信息');
        $model->scenario = 'update_state';
        if($param['type']>1){ //删除
            $data['status']=3;
            $data['deleted_at'] = time();
        }else{ // 编辑停启用
            $info = $model->toArray();
            if($info['status']==1){
                $data['status'] = 2; //停用
            }elseif($info['status']==2){
                $data['status'] = 1; // 启用
            }else{
                return array('error'=>'参数错误,请重新刷新页面再次请求');
            }

        }
        $model->setAttributes($data, false);
        if (!$model->save()) {
            return array('error'=>'操作失败');
        }else{
            return array('error'=>'');
        }


    }


    /**
     * 新增与编辑项目信息
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editProjectInfo($param){
        try{
            $t = static::getDb()->beginTransaction();
            if($param['type']>1){ //编辑
                $model = static::findOne(['id' =>$param['id']]);
                if(empty($model)) return array('error'=>'未查询到相关信息');
                if($param['type']==3){
                    $model->scenario = 'update_project_analyse';
                }else{
                    $model->scenario = 'update';
                }

            }else{
                $model = new self();
                $model->scenario = 'create';
                unset($param['id']);
            }
            if(!empty($param['tags'])){
                $project_type = new ProjectType();
                $effective_tags = $project_type->find()->where(['status'=>1,'deleted_at'=>null])->asArray()->all();
                $effective_tags_ids = [];
                if(count($effective_tags)){
                    $effective_tags_ids = array_column($effective_tags,'id');
                }
                $tags = explode(',',$param['tags']);
                foreach($tags as $key=>$value){
                    if(!in_array($value,$effective_tags_ids)){
                        return array('error'=>'标签值无效');
                    }
                }
                $param['tags']=serialize($tags);
            }
            if(!empty($param['release_time'])){
                $param['release_time'] = strtotime($param['release_time']);
            }
            $model->setAttributes($param, false);
            if (!$model->save()) {
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (\Exception $e){
            return array('error'=>'操作失败');
        }

    }



}
